<template>
  <div class="main">
    <!-- 标题 -->
    <Title :title="title" />
    <!-- 应聘意向 -->
    <Card
      :title="targetForm.title"
      :icon-src="targetForm.image"
      :custom-style="{ width: '23px', height: '24px' }"
    >
      <my-form

        slot="content"
        :ref-obj.sync="targetForm.ref"
        :form-opts="targetForm"
        :width-size="3"
        @handleEvent="handleTargetEvent"
      />
    </Card>
    <!-- 个人信息表单 -->
    <Card
      :title="userForm.title"
      :icon-src="userForm.image"
      :custom-style="{ width: '25px', height: '20px' }"
    >
      <my-form
        slot="content"
        :ref-obj.sync="userForm.ref"
        :form-opts="userForm"
        :width-size="4"
        @handleEvent="handleUserEvent"
      >
        <div slot="right" class="pic">
          <el-upload
            class="pic-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="userForm.formData.avatar"
              :src="baseURL + userForm.formData.avatar"
              class="avatar"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <span>只支持.jpg/png格式</span>
        </div>
      </my-form>
    </Card>
    <!-- 配偶信息 -->
    <Card
      :title="mateForm.title"
      :icon-src="mateForm.image"
      :custom-style="{ width: '24px', height: '20px' }"
    >
      <my-form
        slot="content"
        :ref-obj.sync="mateForm.ref"
        :form-opts="mateForm"
        :width-size="3"
        @handleEvent="handleMateEvent"
      />
    </Card>
    <!-- 教育经历 -->
    <Card
      :title="educationData.title"
      :icon-src="educationData.image"
      :custom-style="{ width: '24px', height: '24px' }"
    >
      <div slot="content">
        <TableForm
          ref="educationTableForm"
          :config="educationData"
          style="margin: 20px"
          @submit="educationSubmit"
        />
        <div class="btn-group">
          <div class="add-btn" @click="handleAdd('educationTableForm')">
            <span class="add-icon">+</span>
            <span>增加行数</span>
          </div>
          <div
            class="upload-btn"
            @click="
              handleDownload('教育经历模版', fieldList.educationTableForm)
            "
          >
            <i class="el-icon-download" />
            <span>下载模版</span>
          </div>
          <div class="upload-btn" @click="handleUpload('educationTableForm')">
            <i class="el-icon-upload2" />
            <span>上传模版</span>
          </div>
        </div>
      </div>
    </Card>
    <!-- 工作经历 -->
    <Card
      :title="workData.title"
      :icon-src="workData.image"
      :custom-style="{ width: '24px', height: '20px' }"
    >
      <div slot="content">
        <TableForm
          ref="workTableForm"
          :config="workData"
          style="margin: 20px"
          :has-index="true"
          @submit="workSubmit"
        />
        <div class="btn-group">
          <div class="add-btn" @click="handleAdd('workTableForm')">
            <span class="add-icon">+</span>
            <span>增加行数</span>
          </div>
          <div
            class="upload-btn"
            @click="handleDownload('工作经历模版', fieldList.workTableForm)"
          >
            <i class="el-icon-download" />
            <span>下载模版</span>
          </div>
          <div class="upload-btn" @click="handleUpload('workTableForm')">
            <i class="el-icon-upload2" />
            <span>上传模版</span>
          </div>
        </div>
      </div>
    </Card>
    <!-- 工作经历 -->
    <Card
      title="国际学术组织任职或兼职"
      icon-src="images/chair.png"
      :custom-style="{ width: '24px', height: '24px' }"
    >
      <div slot="content">
        <el-input
          v-model="introduce"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 10 }"
          placeholder="请输入内容"
        />
        <!-- <div class="edit_container">
          <quill-editor v-model="ruleForm.words" ref="myQuillEditor" class="editer" :options="editorOption" @ready="onEditorReady($event)">
          </quill-editor>
        </div>  -->

      </div>
    </Card>
    <Main ref="main" />
    <Other />
    <!-- 保存按钮 -->
    <div class="btn-group">
      <el-button type="warning" @click="submitForm(1)">保存</el-button>
      <el-button
        :disabled="isdisable"
        type="primary"
        @click="submitForm(2)"
      >提交</el-button>
    </div>

    <UploadExcel ref="upload" :on-success="onSuccess" />
  </div>
</template>

<script>
import schema from './schema'
import config from './config.js'
import { getToken } from '@/utils/auth'
import { uploadMixin } from '@/mixin/upload'
// import { quillEditor } from 'vue-quill-editor';
// import { quillEditor } from '';
import {
  getRoleMold,
  getRoleType,
  addPersonnelInfo,
  savePersonnelInfo,
  getPersonnelInfo,
  getMainInfo
} from '@/api/personnel'
import Main from '../apply/main/index.vue'
import Other from '../apply/other/index.vue'
import rules from '../role/config.js'

// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'

export default {
  components: {
    Main,
    Other
  },
  mixins: [uploadMixin],
  data () {
    return {
      editorOption: {}, // 富文本变量
      jihao: true,
      jiben_submit_type: '', // 人才基本信息标记变量
      title: '',
      // form表单
      targetForm: schema.targetForm,
      // 用户表单
      userForm: schema.userForm,
      // 配偶信息表单
      mateForm: schema.mateForm,
      // 教育经历表格
      educationData: config.educationData,
      // 工作经历表格
      workData: config.workData,
      // 国际学术组织任职或兼职
      introduce: '',
      teach_undergo: [],
      work_undergo: [],
      uploadUrl: process.env.VUE_APP_IMAGE_UPLOAD_URL,
      headers: {
        token: getToken()
      },
      baseURL: process.env.VUE_APP_BASE_API,
      fieldList: config.fieldList,
      userInfo: {},
      isdisable: false
    }
  },
  created () {
    localStorage.setItem('a', 1)

    this.userInfo = this.$store.getters.userInfo
    // 设置标题
    this.title = this.$route.meta.title
    // 获取应聘单位数据
    this.getRoleMold()
    // 获取应聘岗位
    this.getRoleType()
    // 获取人才信息
    // this.getPersonnelInfo();
  },
  mounted () {
    this.getMainInfo()
    this.targetForm.formData.apply_college = this.userInfo.role_classify
    this.getPersonnelInfo()

    // let arr = document.querySelectorAll(".el-input__inner");
    // arr.forEach((item) => {
    //   item.disabled = true;
    //   item.parentNode.classList.add("is-disabled");
    // });
    // document.querySelector(".el-input__inner").disabled = false;
  },
  methods: {
    //  onEditorReady(editor) {
    //    console.log('editor')
    //   },
    // 获取其他信息
    async getMainInfo () {
      const res = await getMainInfo()
      // 主要资料
      console.log(res.data.submit_type)
      if (res.data.submit_type === 1) {
        this.isdisable = true
      } else {
        this.isdisable = false
      }
    },
    // 申请目标选择表单事件
    handleTargetEvent (type, val) {
      switch (type) {
        case 'checkbox':
          console.log('checkbox', val, type)
          break
      }
    },
    // 个人信息表单
    handleUserEvent (type, val) {
      switch (type) {
        case 'checkbox':
          console.log('checkbox', val, type)
          break
      }
    },
    // 配偶信息
    handleMateEvent (type, val) {
      switch (type) {
        case 'checkbox':
          console.log('checkbox', val, type)
          break
      }
    },

    // 提交form表单 type: 1 保存 type: 2提交
    submitForm (type) {
      if (!this.userForm.formData.avatar) {
        return this.$message.error('请上传照片')
      }
      this.$refs.workTableForm.submit()
      this.$refs.educationTableForm.submit()

      this.targetForm.ref.validate((valid) => {
        if (!valid) return
        this.userForm.ref.validate((valid) => {
          if (!valid) return
          this.mateForm.ref.validate((valid) => {
            if (!valid) return
            // 人才基本数据
            const userData = JSON.parse(JSON.stringify(this.userForm.formData))
            // 配偶数据
            const mateData = JSON.parse(JSON.stringify(this.mateForm.formData))
            userData.birth_time =
              new Date(userData.birth_time).getTime() / 1000
            mateData.spouse_birth_time =
              new Date(mateData.spouse_birth_time).getTime() / 1000
            // 筛选掉未填入数据的空行
            const teachUndergoNoEmpty = []
            this.teach_undergo.forEach((item, index) => {
              const flag = Object.keys(this.teach_undergo[0]).every((key) => {
                return !item[key]
              })
              if (!flag) {
                teachUndergoNoEmpty.push(item)
              }
            })
            const workUndergoNoEmpty = []
            this.work_undergo.forEach((item, index) => {
              const flag = Object.keys(this.work_undergo[0]).every((key) => {
                return !item[key]
              })
              if (!flag) {
                workUndergoNoEmpty.push(item)
              }
            })
            const data = {
              ...this.targetForm.formData,
              ...userData,
              ...mateData,
              introduce: this.introduce,
              teach_undergo: JSON.stringify(teachUndergoNoEmpty),
              work_undergo: JSON.stringify(workUndergoNoEmpty)
            }
            delete data.states
            delete data.submit_type
            if (type === 1) {
              // 保存
              this.savePersonnelInfo(data)
              this.$refs.main.handleSubmit(1)
            } else {
              // 提交
              this.addPersonnelInfo(data)
              this.$refs.main.handleSubmit(2)
            }
          })
        })
      })
    },
    // 重置form表单
    resetForm () {
      Object.assign(
        this.$data.formOpts.formData,
        this.$options.data().formOpts.formData
      )
      // 清空校验
      this.formOpts.ref.clearValidate()
    },
    // 清除校验
    clearValidate () {
      this.formOpts.ref.clearValidate()
    },
    handleAvatarSuccess (res, file) {
      this.userForm.formData.avatar = res.data.url
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      return isJPG
    },
    // 教育经历表格提交
    educationSubmit (res) {
      this.teach_undergo = res
    },
    // 新增行
    handleAdd (name) {
      this.$refs[name].add()
    },
    // 工作经历表格提交
    workSubmit (res) {
      this.work_undergo = res
    },
    // 获取应聘单位
    async getRoleMold () {
      const res = await getRoleMold()
      this.targetForm.listTypeInfo.applyCollegeList = res.data
    },
    // 获取应聘岗位
    async getRoleType () {
      const res = await getRoleType()
      this.targetForm.listTypeInfo.applyPostList = res.data
    },
    // 提交个人信息
    async addPersonnelInfo (data) {
      await addPersonnelInfo(data)
      this.$message.success('保存成功')
    },
    // 保存
    async savePersonnelInfo (data) {
      await savePersonnelInfo(data)
      this.$message.success('提交成功')
    },

    up_options () { // 改变配置项disabled，不能刷新页面会陷入死循环
      schema.targetForm.fieldList[1].disabled = true
      schema.targetForm.fieldList[2].disabled = true
      // 个人
      schema.userForm.fieldList[0].disabled = true
      schema.userForm.fieldList[1].disabled = true
      schema.userForm.fieldList[2].disabled = true
      schema.userForm.fieldList[3].disabled = true
      schema.userForm.fieldList[4].disabled = true
      schema.userForm.fieldList[5].disabled = true
      schema.userForm.fieldList[6].disabled = true
      schema.userForm.fieldList[7].disabled = true
      schema.userForm.fieldList[8].disabled = true
      schema.userForm.fieldList[9].disabled = true
      schema.userForm.fieldList[10].disabled = true
      schema.userForm.fieldList[11].disabled = true
      schema.userForm.fieldList[12].disabled = true
      schema.userForm.fieldList[13].disabled = true
      schema.userForm.fieldList[14].disabled = true
      schema.userForm.fieldList[15].disabled = true
      schema.userForm.fieldList[16].disabled = true
      schema.userForm.fieldList[17].disabled = true
      // 配偶
      schema.mateForm.fieldList[0].disabled = true
      schema.mateForm.fieldList[1].disabled = true
      schema.mateForm.fieldList[2].disabled = true
      schema.mateForm.fieldList[3].disabled = true
      schema.mateForm.fieldList[4].disabled = true

      // 教育经历
      config.educationData.columns[0].disabled = true
      config.educationData.columns[1].disabled = true
      config.educationData.columns[2].disabled = true
      config.educationData.columns[3].disabled = true
      config.educationData.columns[4].disabled = true
      config.educationData.columns[5].disabled = true
      // 工作经历
      config.workData.columns[0].disabled = true
      config.workData.columns[1].disabled = true
      config.workData.columns[2].disabled = true
      config.workData.columns[3].disabled = true
      config.workData.columns[4].disabled = true
      config.workData.columns[5].disabled = true
    },

    // 获取人才基本信息
    async getPersonnelInfo () {
      const res = await getPersonnelInfo()
      if (!res.data) return
      // console.log('====>',res)
      res.data.spouse_birth_time = new Date(res.data.spouse_birth_time * 1000)
      res.data.birth_time = new Date(res.data.birth_time * 1000)
      this.jiben_submit_type = res.data.submit_type // 人才基本信息标记量
      console.log(res.data.submit_type, '是否填写过资料')
      if (res.data.submit_type == 1) { // 已经提交过
        localStorage.setItem('is_select', 1)
        this.up_options()

        // if(localStorage.getItem('a')==1){
        //   location.reload()
        //   localStorage.setItem('a', 2)
        // }
        // console.log('kkkk',res.data.submit_type,'===>')
        // location.reload(true)

        // this.$nextTick(function(){

        // });
        // location.reload()
        // this.$router.go(0)
      } else {
        console.log('qqq', res.data.submit_type)
        localStorage.setItem('is_select', 0)
        // location.reload()
        // this.$router.go(0)
      }

      const {
        spouse_name,
        spouse_birth_time,
        spouse_degree,
        spouse_unit,
        spouse_school

      } = res.data
      this.targetForm.formData = res.data
      this.userForm.formData = res.data
      this.mateForm.formData = {
        spouse_name,
        spouse_birth_time,
        spouse_degree,
        spouse_unit,
        spouse_school
      }
      const { teach_undergo, work_undergo, introduce } = res.data
      teach_undergo && this.$refs.educationTableForm.setData(teach_undergo)
      work_undergo && this.$refs.workTableForm.setData(work_undergo)
      this.introduce = introduce
    },

    // 上传成功的回调函数
    onSuccess (e) {
      let dataStr = JSON.stringify(e.results)
      Object.keys(this.fieldList[this.currentUpload]).forEach((key) => {
        dataStr = dataStr.replace(key, this.fieldList[this.currentUpload][key])
      })
      const data = JSON.parse(dataStr)
      this.$refs[this.currentUpload].setData(data, true)
    }
  }
}
</script>
<style lang="scss" scoped>
.pic {
  span {
    padding-left: 60px;
    font-size: 14px;
    font-family: MicrosoftYaHei;
    font-weight: 400;
    color: #999999;
    box-sizing: border-box;
  }
}
.pic-uploader {
  margin: 0 40px 15px 60px;
  background-color: #f5f5f5;
  ::v-deep.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 172px;
    height: 184px;
    line-height: 184px;
    text-align: center;
  }
}
.avatar {
  width: 172px;
  height: 184px;
  display: block;
}

.btn-group {
  display: flex;
  align-items: center;
  margin-top: 20px;
  font-size: 16px;

  .add-btn {
    display: flex;
    align-items: center;
    color: #2860c3;
    cursor: pointer;
    .add-icon {
      position: relative;
      top: -2px;
    }
  }
  .upload-btn {
    margin-left: 30px;
    cursor: pointer;
  }
}

.save-btn {
  width: 110px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #ef8334;
  border-radius: 3px;

  font-size: 14px;
  font-family: MicrosoftYaHei;
  font-weight: 400;
  color: #ffffff;
  cursor: pointer;
}

.btn-group {
  display: flex;
  align-items: center;
}
</style>
